<?php

namespace App\Http\Controllers\Home;

use App\Models\JifenDetail;
use App\Models\Transition;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;

/**
 * @group 前台接口文档
 * @title 支付模块接口
 * @author chenke
 * @description 酒庄前台支付板块接口
 * @header name:Token type:string require:1 desc:登录令牌
 * @header name:Lang type:string require:1 desc:语言类型(en或zn)
 *  */
class Pay extends Base
{
    /**
     * @title 发起交易
     * @description 前台输入支付密码前先发起交易
     * @url /api/pay/crepay
     * @method POST
     * @module 支付板块
     * @author chenke
     * @param name:orderid type:int require:1 default:0 other: desc:订单ID,无订单时传0
     * @param name:transtype type:int require:1 default: other: desc:交易类型1为预定订单订金付款、2为预定订单结账付款、3为商品订单付款、4为充值、5为反馈转钱包、6为反馈、7为提现、8佣金、9退款
     * @param name:paytype type:int require:1 default: other: desc:支付类型0无需支付、1为钱包支付、2为反馈钱包支付、3为现金支付
     * @param name:number type:int require:1 default: other: desc:交易金额
     * @return code:错误码
     * @return message:错误提示
     * @return data: 交易单号
     */
    public function toTrans(Request $request){
        $lang = $request->header('Lang')?$request->header('Lang'):'zn';
        try {
            $data = $request->post();
            $rules = [
                'orderid'=>'required|integer',
                'paytype'=>[
                    'required',Rule::in([0,1,2,3,])
                ],
                'transtype'=>[
                    'required',Rule::in([1,2,3,4,5,6,7,8,9])
                ],
                'number'=>[
                    'required','integer'
                ]
            ];
            $messages = [
                'orderid.required'=>  $this->lang['REQUIRED'][$lang],
                'transtype.required'=>  $this->lang['REQUIRED'][$lang],
                'orderid.integer'=> $this->lang['INTEGER'][$lang],
                'transtype.in'=> $this->lang['IN'][$lang],
                'number.required'=>  $this->lang['REQUIRED'][$lang],
                'number.integer'=>  $this->lang['INTEGER'][$lang],
                'paytype.required'=>  $this->lang['REQUIRED'][$lang],
                'paytype.in'=>  $this->lang['IN'][$lang],
            ];
            $check = $this->checkParams($data,$rules,$messages);
            if($check['code']){
                return response()->json($check);
            }
            $user = (new User())->where('token',$request->token)->select('id','deleted_at')->first();
            if(!$user){
                return response()->json([
                    'code'=>50000,
                    'message'=>$this->lang['LOGIN_EXPIRE'][$lang]
                ]);
            }
            if($user->deleted_at){
                return [
                    'code'=>1,
                    'message'=>$this->lang['USER_FORBIDDEN'][$lang]
                ];
            }
            $data['uid'] = $user->id;
            $result =  (new Transition())->transAdd($data,$lang);
            if($result['code']){
                $this->logErr($result['code'],$result['message'],'toTrans');
            }
            return response()->json($result);
        }catch (\Exception $e){
            return response()->json([
                'code'=>1,
                'message'=>$e->getMessage()// $this->lang['ERROR'][$lang]
            ]);
        }
    }

    /**
     * @title 交易完成
     * @description 前台输入支付密码前先发起交易
     * @url /api/pay/transed
     * @method POST
     * @module 支付板块
     * @author chenke
     * @param name:sign type:string require:1 default:0 other: desc:交易签名(含交易单号transno,交易密码paypass,交易时间完成时间expired,交易授权signkey,交易金额number,交易类型transtype(1,3,4,5,7),支付类型paytype(1,2))
     * @return code:错误码
     * @return message:错误提示
     * @return data: 交易信息@
     * @data transno:交易单号 number:交易金额
     */
    public function transComplete(Request $request){
        try {
            $data = $request->post();
            $rules = [
                'sign'=>'required|string'
            ];
            $messages = [
                'sign.required'=>  $this->lang['REQUIRED'][$request->lang]
            ];
            $check = $this->checkParams($data,$rules,$messages);
            if($check['code']){
                return response()->json($check);
            }
            //判断用户是否可用
            $user = (new User())->where('token',$request->token)->first();
            if(!$user){
                return [
                    'code'=>50000,
                    'message'=>$this->lang['LOGIN_EXPIRE'][$request->lang]
                ];
            }
            if($user->deleted_at){
                return [
                    'code'=>1,
                    'message'=>$this->lang['USER_FORBIDDEN'][$request->lang]
                ];
            }
            $sign = $data['sign'];
            //签名数据解密
            $signData = $this->decreSign($sign,$request->lang);
            if($signData['code']){
                return response()->json($signData);
            }
            $traninfo = $signData['data'];
            //验证支付密码
            if(!Hash::check($traninfo['paypass'],$user->paypass)){
                return [
                    'code'=>1,
                    'message'=>$this->lang['PAY_ERR'][$request->lang]
                ];
            }
            $result =  (new Transition())->transComplete($traninfo,$user,$request->lang);
            if($result['code']){
                $this->logErr($result['code'],$result['message'],'toTrans');
            }
            return response()->json($result);
        }catch (\Exception $e){
            return response()->json([
                'code'=>1,
                'message'=>$this->lang['ERROR'][$request->lang]
            ]);
        }
    }

    /**
     * @title 积分支付完成
     * @description 前台输入支付密码前先发起积分交易
     * @url /api/pay/jtransed
     * @method POST
     * @module 支付板块
     * @author chenke
     * @param name:sign type:string require:1 default:0 other: desc:交易签名(含交易单号transno,交易密码paypass,交易时间完成时间expired,交易授权signkey,支付数量number)
     * @return code:错误码
     * @return message:错误提示
     * @return data: 交易信息@
     * @data transno:交易单号 number:交易数量
     */
    public function jifenTransComplete(Request $request){
        try {
            $data = $request->post();
            $rules = [
                'sign'=>'required|string'
            ];
            $messages = [
                'sign.required'=>  $this->lang['REQUIRED'][$request->lang]
            ];
            $check = $this->checkParams($data,$rules,$messages);
            if($check['code']){
                return response()->json($check);
            }
            //判断用户是否可用
            $user = (new User())->where('token',$request->token)->first();
            if(!$user){
                return [
                    'code'=>50000,
                    'message'=>$this->lang['LOGIN_EXPIRE'][$request->lang]
                ];
            }
            if($user->deleted_at){
                return [
                    'code'=>1,
                    'message'=>$this->lang['USER_FORBIDDEN'][$request->lang]
                ];
            }
            $sign = $data['sign'];
            //签名数据解密
            $signData = $this->decreSign($sign,$request->lang);
            if($signData['code']){
                return response()->json($signData);
            }
            $traninfo = $signData['data'];
            //验证支付密码
            if(!Hash::check($traninfo['paypass'],$user->paypass)){
                return [
                    'code'=>1,
                    'message'=>$this->lang['PAY_ERR'][$request->lang]
                ];
            }
            $result =  (new JifenDetail())->transComplete($traninfo,$user,$request->lang);
            if($result['code']){
                $this->logErr($result['code'],$result['message'],'toTrans');
            }
            return response()->json($result);
        }catch (\Exception $e){
            return response()->json([
                'code'=>1,
                'message'=>$this->lang['ERROR'][$request->lang]
            ]);
        }
    }


    /**
     * @title 发起积分交易
     * @description 前台输入支付密码前先发起交易
     * @url /api/pay/crejpay
     * @method POST
     * @module 支付板块
     * @author chenke
     * @param name:orderid type:int require:1 default:0 other: desc:订单ID,无订单时传0
     * @param name:transtype type:int require:1 default: other: desc:交易类型1为积分兑换、2为反馈积分
     * @param name:number type:int require:1 default: other: desc:交易数量或交易金额
     * @param name:paytype type:int require:1 default: other: desc:支付类型(0无需支付1钱包支付2反馈钱包支付3积分兑换)
     * @return code:错误码
     * @return message:错误提示
     * @return data: 交易单号
     */
    public function toJefenTrans(Request $request){
        $lang = $request->header('Lang')?$request->header('Lang'):'zn';
        try {
            $data = $request->post();
            $rules = [
                'orderid'=>'required|integer',
                'paytype'=>[
                    'required',Rule::in([1,2,3])
                ],
                'transtype'=>[
                    'required',Rule::in([1,2])
                ],
                'number'=>[
                    'required','integer'
                ]
            ];
            $messages = [
                'orderid.required'=>  $this->lang['REQUIRED'][$lang],
                'transtype.required'=>  $this->lang['REQUIRED'][$lang],
                'orderid.integer'=> $this->lang['INTEGER'][$lang],
                'transtype.in'=> $this->lang['IN'][$lang],
                'number.required'=>  $this->lang['REQUIRED'][$lang],
                'number.integer'=>  $this->lang['INTEGER'][$lang],
                'paytype.required'=>  $this->lang['REQUIRED'][$lang],
                'paytype.in'=>  $this->lang['IN'][$lang],
            ];
            $check = $this->checkParams($data,$rules,$messages);
            if($check['code']){
                return response()->json($check);
            }
            //获取用户信息
            $user = (new User())->where('token',$request->token)->first();
            if(!$user){
                return [
                    'code'=>50000,
                    'message'=>$this->lang['LOGIN_EXPIRE'][$request->lang]
                ];
            }
            if($user->deleted_at){
                return [
                    'code'=>1,
                    'message'=>$this->lang['USER_FORBIDDEN'][$lang]
                ];
            }
            $result =  (new JifenDetail())->transAdd($data,$user,$lang);
            if($result['code']){
                $this->logErr($result['code'],$result['message'],'toJefenTrans');
            }
            return response()->json($result);
        }catch (\Exception $e){
            return response()->json([
                'code'=>1,
                'message'=>$this->lang['ERROR'][$lang]
            ]);
        }
    }

    /**
     * @title 积分交易记录分页列表
     * @description 前台积分交易记录
     * @url /api/pay/jtrans
     * @method GET
     * @module 积分板块
     * @param name:limit type:int require:1 default:1 other: desc:每页数据条数
     * @param name:page type:int require:1 default:1 other: desc:当前页数
     * @author chenke
     * @return code:错误码
     * @return message:错误提示
     * @return data:交易数据@
     * @data number:交易数量 transtype:交易类型 paytype:支付方式 transname:交易名称 transno:交易编号 coin:交易后剩余积分
     */
    public function jifenTransList(Request $request){
        $lang = $request->header('lang')?$request->header('lang'):'zn';
        try {
            $data = $request->all();
            $limit = $data['limit'];
            $page = $data['page'];
            $user = (new User())->where('token',$request->token)->select('id','deleted_at')->first();
            if(!$user){
                return [
                    'code'=>50000,
                    'message'=>$this->lang['LOGIN_EXPIRE'][$request->lang]
                ];
            }
            if($user->deleted_at){
                return response()->json([
                    'code'=>1,
                    'message'=>$this->lang['USER_FORBIDDEN'][$lang]
                ]);
            }
            $model = (new JifenDetail())->where([
                ['uid','=',$user->id],['status','=',2]
            ]);
            $offset = ($page-1) * $limit;
            $total =  $model->count();  //获取模型总数据条数
            $result = $model->offset($offset)->limit($limit)->orderBy('updated_at','desc')->get()->toArray();
            $data = array(
                'total'=>$total,
                'list'=>$result
            );
            return response()->json([
                'code'=>0,
                'message'=>$data
            ]);
        }catch (\Exception $e){
            return response()->json([
                'code'=>1,
                'message'=>$this->lang['ERROR'][$lang]
            ]);
        }
    }

    /**
     * @title 积分兑换记录分页列表
     * @description 前台积分兑换记录
     * @url /api/pay/exchange
     * @method GET
     * @module 积分板块
     * @param name:limit type:int require:1 default:1 other: desc:每页数据条数
     * @param name:page type:int require:1 default:1 other: desc:当前页数
     * @author chenke
     * @return code:错误码
     * @return message:错误提示
     * @return data:交易数据@
     * @data transno:交易单号 orderid:订单ID proname:商品英文名 proname_zn:商品中文名 image:商品图片 ordersn:订单编号 procoin:交易积分数量 status:订单状态(1待付款2待发货3待收货4已完成5已取消6已退) pronum:兑换数量
     */
    public function jifenExchange(Request $request){
        $lang = $request->header('lang')?$request->header('lang'):'zn';
        try {
            $data = $request->all();
            $limit = $data['limit'];
            $page = $data['page'];
            $user = (new User())->where('token',$request->token)->select('id','deleted_at')->first();
            if(!$user){
                return [
                    'code'=>50000,
                    'message'=>$this->lang['LOGIN_EXPIRE'][$request->lang]
                ];
            }
            if($user->deleted_at){
                return response()->json([
                    'code'=>1,
                    'message'=>$this->lang['USER_FORBIDDEN'][$lang]
                ]);
            }
            $model = (new JifenDetail())->leftJoin('prod_orders','prod_orders.id','=','jifen_details.orderid')
                    ->leftJoin('products','products.id','=','prod_orders.proid')
                    ->where([ ['jifen_details.uid','=',$user->id],['transtype','=',1],['prod_orders.deleted_at','=',null] ])
                    ->select('jifen_details.transno','jifen_details.orderid','products.proname','products.proname_zn','products.image','prod_orders.ordersn','prod_orders.procoin','prod_orders.status','prod_orders.pronum');
            $offset = ($page-1) * $limit;
            $total =  $model->count();  //获取模型总数据条数
            $result = $model->offset($offset)->limit($limit)->orderBy('jifen_details.updated_at','desc')->get()->toArray();
            $data = array(
                'total'=>$total,
                'list'=>$result
            );
            return response()->json([
                'code'=>0,
                'message'=>$data
            ]);
        }catch (\Exception $e){
            return response()->json([
                'code'=>1,
                'message'=>$this->lang['ERROR'][$lang]
            ]);
        }
    }
}
